import pygame
import sys

from common import (
    font_path,
    black,
    red,
    white,
    blue,
    set_score,
    get_score,
    add_score,
    go_next_level,
)

screen_width, screen_height = 1300, 750


def is_success():
    for index, target_rect in enumerate(target_rects):
        if index == 11:
            continue
        _, num_rect, _ = numbers[index]
        if not target_rect.collidepoint(num_rect.center):
            return False
    return True


def reset():
    global font, numbers, target_rects, dragging, offset_x, offset_y, running, start_ticks, elapsed_time, cost_time, button_text, button_rect, pre_image, cur_image
    set_score(100)

    # 设置屏幕大小和标题

    pygame.display.set_caption("请将数字放置到正确的位置")

    # 设置字体和颜色
    font = pygame.font.Font(font_path, 36)
    # 数字网格的初始化
    spacing = 80
    numbers = []
    start_x, start_y = 500, 50  # Adjust start position for numbers grid
    for i in range(1, 14):  # Create numbers 1 to 16
        x = start_x + ((i - 1) % 4) * spacing
        y = start_y + ((i - 1) // 4) * spacing
        number_image = font.render(str(i), True, black)
        number_rect = number_image.get_rect(topleft=(x, y))
        numbers.append((number_image, number_rect, (x, y)))

    target_rects = [
        pygame.Rect(165, 565, 50, 50),  # 1
        pygame.Rect(992, 610, 50, 50),  # 2
        pygame.Rect(218, 610, 50, 50),  # 3
        pygame.Rect(940, 567, 50, 50),  # 4
        pygame.Rect(305, 610, 50, 50),  # 5
        pygame.Rect(880, 617, 50, 50),  # 6
        pygame.Rect(350, 565, 50, 50),  # 7
        pygame.Rect(825, 557, 50, 50),  # 8
        pygame.Rect(410, 557, 50, 50),  # 9
        pygame.Rect(765, 500, 50, 50),  # 10
        pygame.Rect(447, 617, 50, 50),  # 11
        pygame.Rect(10000, 10000, 50, 50),  # 12
        pygame.Rect(460, 500, 50, 50),  # 13
    ]

    # Initialize dragging state
    dragging = None
    offset_x = 0
    offset_y = 0

    # Timer initialization
    running = False
    start_ticks = 0
    elapsed_time = 0
    cost_time = 0

    # Start game button
    button_text = font.render("开始计时", True, blue)
    button_rect = button_text.get_rect(center=(300, 150))

    # 游戏图片
    pre_image = pygame.image.load("./assets/game_3/start.png")

    cur_image = pre_image


reset()


def draw(screen):
    global cur_image, dragging, elapsed_time, running, start_ticks, numbers, offset_x, offset_y, cost_time
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):
                if not running:
                    running = True
                    start_ticks = pygame.time.get_ticks()
            for index, (img, rect, orig_pos) in enumerate(numbers):
                if rect.collidepoint(event.pos) and running:
                    dragging = index
                    mouse_x, mouse_y = event.pos
                    offset_x = rect.x - mouse_x
                    offset_y = rect.y - mouse_y
                    break
        elif event.type == pygame.MOUSEBUTTONUP:
            # if the mouse is released over a target rect, set the number to the target rect
            for rect in target_rects:
                if rect.collidepoint(event.pos) and dragging is not None:
                    img, num_rect, orig_pos = numbers[dragging]
                    num_rect.center = rect.center
                    numbers[dragging] = (img, num_rect, orig_pos)
                    if target_rects.index(rect) != dragging:
                        add_score(-10)
                    dragging = None

            if dragging is not None:
                # Reset to original position
                img, rect, orig_pos = numbers[dragging]
                rect.topleft = orig_pos
                numbers[dragging] = (img, rect, orig_pos)
                dragging = None
        elif event.type == pygame.MOUSEMOTION:
            if dragging is not None:
                mouse_x, mouse_y = event.pos
                numbers[dragging][1].x = mouse_x + offset_x
                numbers[dragging][1].y = mouse_y + offset_y

    # 更新屏幕显示
    screen.fill(white)
    # 绘制游戏图片
    screen.blit(cur_image, (20, 400))
    screen.blit(button_text, button_rect)

    # 显示数字网格
    for img, rect, _ in numbers:
        screen.blit(img, rect)

    # 计时器显示
    if running:
        total_seconds = (pygame.time.get_ticks() - start_ticks + elapsed_time) // 1000
        cost_time = total_seconds
    else:
        total_seconds = elapsed_time // 1000

    minutes = total_seconds // 60
    seconds = total_seconds % 60
    time_string = f"{minutes:02}:{seconds:02}"
    time_text = font.render(time_string, True, red)
    time_rect = time_text.get_rect(center=(300, 250))
    screen.blit(time_text, time_rect)

    # 显示当前分数
    score_text = font.render(f"当前分数: {get_score()}", True, red)
    score_rect = score_text.get_rect(center=(1000, 200))
    screen.blit(score_text, score_rect)

    # 显示目标区域
    # for target_rect in target_rects:
    #     pygame.draw.rect(screen, yellow, target_rect, 2)

    pygame.display.flip()

    if is_success():
        running = False
        pygame.time.delay(1000)
        go_next_level()
